package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.UserDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.utils.PasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl extends LogicService<UserDao, User, Long> implements IUserService {
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    public UserServiceImpl(@Autowired UserDao dao) {
        super(dao);
    }

    @Override
    public User register(User user) {
        if (getDAO().findByUsername(user.getUsername()) != null) {
            throw new RuntimeException("Username already exists");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return getDAO().save(user);
    }

    @Override
    public User login(String username, String password) {
        User user = getDAO().findByUsername(username);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            return user;
        }
        return null;
    }
} 